﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using NTQOnlineExam.Services.EntityFW.Context;
using NTQOnlineExam.Services.EntityFW.Entity;
using NTQOnlineExam.Services.EntityFW.Repository;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;
using NTQOnlineExam.Services.ReportService.Account;
using NTQOnlineExam.Services.SearchCriteria;

namespace NTQOnlineExam.Services.ReportService.Order
{
    public class OrderReportService : IOrderReportService
    {
        private readonly ICommandExecutor _executor;
        private readonly IGenericRepository<OrderDetail> _orderDetailRepository;
        private readonly IAccountReportService _accountReportService;
        public OrderReportService(ICommandExecutor executor, IGenericRepository<OrderDetail> orderDetailRepository, IAccountReportService accountReportService, IGenericRepository<EntityFW.Entity.Order> orderRepository)
        {
            _executor = executor;
            _orderDetailRepository = orderDetailRepository;
            _accountReportService = accountReportService;
        }

        public SearchResult<OrderDTO> SearchOrder(OrderSearchCriteria criteria, int pageSize, int pageIndex, out decimal totalOrderAmount)
        {
            totalOrderAmount = 0;
            var result = _executor.Execute(new SearchOrderByCriteriaDbCommand(criteria, pageSize, pageIndex));
            if (result == null) return new SearchResult<OrderDTO>(new List<OrderDTO>(), 0);
            totalOrderAmount = result.TotalOrderAmount;
            return result.Result;
        }

        public OrderDTO GetOrderById(Guid orderId)
        {
            var order = _executor.Execute(new GetOrderByIdDbCommand(orderId));
            if (order != null)
            {
                order.OrderDetails = GetOrderDetailsByOrderId(orderId);
                return order;
            }
            return new OrderDTO();
        }

        public IList<OrderDetailDTO> GetOrderDetailsByOrderId(Guid orderId)
        {
            var list = _orderDetailRepository.Get(x => x.OrderId == orderId);
            return list.Select(Mapper.Map<OrderDetail, OrderDetailDTO>).ToList();
        }

        public IList<OrderDTO> GetCurrentUserOrderHistory(IList<SearchSortItem> sortItems, int pageSize, int pageIndex, out int total)
        {
            total = 0;
            var user = _accountReportService.GetCurrentUser();
            if (user == null) return new List<OrderDTO>();
            var result = _executor.Execute(new GetOrderHistoryByUserDbCommand(sortItems, (int)user.ProviderUserKey, pageSize, pageIndex));
            if (result == null) return new List<OrderDTO>();
            total = result.Count;
            return result.Items;
        }
    }
}
